package com.cloudweb.oa.controller;

import cn.js.fan.db.Paginator;
import cn.js.fan.security.ThreeDesUtil;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;
import cn.js.fan.web.Global;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.cache.DepartmentCache;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.cache.UserSetupCache;
import com.cloudweb.oa.entity.Department;
import com.cloudweb.oa.entity.OaMessageDept;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.IFileService;
import com.cloudweb.oa.service.IOaMessageDeptService;
import com.cloudweb.oa.thread.PreviewGenerateThread;
import com.cloudweb.oa.utils.*;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.util.IPUtil;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.kit.util.FileInfo;
import com.redmoon.kit.util.FileUpload;
import com.redmoon.oa.Config;
import com.redmoon.oa.flow.Leaf;
import com.redmoon.oa.flow.MyActionDb;
import com.redmoon.oa.flow.WorkflowDb;
import com.redmoon.oa.message.*;
import com.redmoon.oa.person.UserDb;
import com.redmoon.oa.person.UserMgr;
import com.redmoon.oa.person.UserSetupDb;
import com.redmoon.oa.pvg.Privilege;
import com.redmoon.oa.security.SecurityUtil;
import com.redmoon.oa.ui.SkinMgr;
import com.redmoon.oa.visual.ModuleSetupDb;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Api(tags = "消息")
@Controller
@RequestMapping("/message_oa")
public class MessageController {
    @Autowired
    HttpServletRequest request;

    @Autowired
    private IFileService fileService;

    @Autowired
    private ResponseUtil responseUtil;

    @Autowired
    private UserCache userCache;

    @Autowired
    private AuthUtil authUtil;

    @Autowired
    private IOaMessageDeptService oaMessageDeptService;

    @Autowired
    private DepartmentCache departmentCache;

    @Autowired
    SysUtil sysUtil;

    @ApiOperation(value = "下载附件", notes = "下载附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "msgId", value = "消息ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "attachId", value = "附件ID", required = true, dataType = "Integer"),
    })
    @RequestMapping("/download")
    public void download(HttpServletResponse response, @RequestParam Integer msgId, @RequestParam Integer attachId) throws IOException, ErrMsgException {
        MessageMgr mm = new MessageMgr();
        MessageDb md = mm.getMessageDb(msgId);
        Attachment att = md.getAttachment(attachId);
        if (StrUtil.isImage(StrUtil.getFileExt(att.getDiskName()))) {
            /*try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
                // 因为不支持<img src='...'/>，故注释掉
                response.setContentType("text/html;charset=utf-8");
                String str = "<img src=\"" + request.getContextPath() + "/showImg.do?path=" + att.getVisualPath() + "/" + att.getDiskName() + "\" />";
                bos.write(str.getBytes(StandardCharsets.UTF_8));
            } catch (final IOException e) {
                LogUtil.getLog(getClass()).error(e);
            }*/
            fileService.preview(response, att.getVisualPath() + "/" + att.getDiskName());
            return;
        }

        fileService.download(response, att.getName(), att.getVisualPath(), att.getDiskName());
    }

    @ApiOperation(value = "删除至垃圾箱", notes = "删除至垃圾箱", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/delToDustbin", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> delToDustbin() {
        boolean re;
        try {
            MessageMgr messageMgr = new MessageMgr();
            re = messageMgr.doDustbin(request, true);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "删除", notes = "删除", httpMethod = "GET")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> del() {
        boolean re;
        try {
            MessageMgr messageMgr = new MessageMgr();
            re = messageMgr.delMsg(request);
        } catch (ErrMsgException e) {
            return new Result<>(false);
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "删除聊天", notes = "删除聊天", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/delChat", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> delChat() {
        boolean re;
        try {
            MessageMgr messageMgr = new MessageMgr();
            re = messageMgr.doChat(request, true);
        } catch (ErrMsgException e) {
            return new Result<>(false);
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "设置已读", notes = "删除聊天室", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ID，以逗号分隔", required = true, dataType = "String"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/batchRead", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> batchRead(@RequestParam(value = "ids") String ids) {
        MessageDb md = new MessageDb();
        String[] newIds = ids.split(",");
        for (String newId : newIds) {
            md = (MessageDb) md.getMessageDb(StrUtil.toInt(newId));
            md.setReaded(true);
            md.save();
        }
        return new Result<>(true);
    }

    @ApiOperation(value = "设置已读", notes = "删除聊天室", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isReaded", value = "是否已读", required = true, dataType = "Boolean"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/setReaded", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> setReaded(@RequestParam Boolean isReaded) {
        String ids = ParamUtil.get(request, "ids");
        if (ids == null) {
            return new Result<>(false);
        }
        MessageDb md = new MessageDb();
        String[] newIds = ids.split(",");
        for (String newId : newIds) {
            md = (MessageDb) md.getMessageDb(StrUtil.toInt(newId));
            md.setReaded(isReaded);
            md.save();
        }

        JSONObject json = responseUtil.getResultJson(true);

        // 取出未读的数量，用于收件箱
        boolean isSys = ParamUtil.getBoolean(request, "isSys", false);
        if (!isSys) {
            Privilege privilege = new Privilege();
            String name = privilege.getUser(request);
            String sql = "select id from oa_message where isreaded=0 and box=0 and is_dustbin=0 and type=0 and receiver=" + StrUtil.sqlstr(name);
            int total = md.getObjectCount(sql);
            json.put("total", total);
        }

        return new Result<>(json);
    }

    @ApiOperation(value = "恢复", notes = "恢复", httpMethod = "GET")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/restore", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> restore() {
        boolean re;
        try {
            MessageMgr messageMgr = new MessageMgr();
            re = messageMgr.doDustbin(request, false);
        } catch (ErrMsgException e) {
            return new Result<>(false);
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "发送收条", notes = "发送收条", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "发送收条", dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/sendReceipt", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> sendReceipt(Integer id) {
        boolean re = false;
        try {
            MessageMgr messageMgr = new MessageMgr();
            MessageDb md = messageMgr.getMessageDb(id);
            if (md == null || !md.isLoaded()) {
                return new Result<>(false);
            }
            md.setReceiptState(MessageDb.RECEIPT_RETURNED);
            re = md.save();
            if (re) {
                re = md.sendSysMsg(md.getSender(), "消息回执：" + md.getTitle(), "用户" + md.getReceiver() + "已经阅读了您的消息！");
            }
        } catch (ErrMsgException e) {
            LogUtil.getLog(getClass()).error(e);
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "删除信息至发送人的垃圾箱", notes = "删除信息至发送人的垃圾箱", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/delMsgBySenderDustbin", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> delMsgBySenderDustbin(@RequestParam Integer id) {
        boolean re;
        try {
            MessageMgr messageMgr = new MessageMgr();
            re = messageMgr.delMsgBySenderDustbin(request);
        } catch (ErrMsgException e) {
            return new Result<>(false);
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "系统信息列表页面", notes = "系统信息列表页面", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isRecycle", value = "是否回收站", dataType = "Integer"),
    })
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @RequestMapping(value = "/sysMessageListPage")
    @ResponseBody
    public Result<Object> sysMessageListPage(@RequestParam(defaultValue = "0") Integer isRecycle) {
        JSONObject object = new JSONObject();
        object.put("isRecycle", isRecycle);
        String actionType = ParamUtil.get(request, "actionType");
        String action = ParamUtil.get(request, "action");
        object.put("actionType", actionType);
        object.put("action", action);
        JSONArray arr = MessageMgr.getActionTypes();
        object.put("actionTypes", arr);
        boolean isNav = ParamUtil.getBoolean(request, "isNav", true);
        object.put("isNav", isNav);
        return new Result<>(object);
    }

    @ApiOperation(value = "系统信息列表", notes = "系统信息列表", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/sysMessageList", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> sysMessageList() {
        Privilege privilege = new Privilege();
        String name = privilege.getUser(request);
        String op = ParamUtil.get(request, "op");
        String action = ParamUtil.get(request, "action");
        String orderBy = ParamUtil.get(request, "orderBy");
        String sort = ParamUtil.get(request, "sort");
        if ("".equals(sort)) {
            sort = "desc";
        }
        String kind = ParamUtil.get(request, "kind");
        if ("".equals(kind)) {
            kind = "title";
        }
        String actionType = ParamUtil.get(request, "actionType");
        String what = ParamUtil.get(request, "what");

        MessageDb md = new MessageDb();
        int curpage = ParamUtil.getInt(request, "page", 1);
        int pagesize = ParamUtil.getInt(request, "pageSize", 20);

        JSONArray ary = new JSONArray();
        int isRecycle = ParamUtil.getInt(request, "isRecycle", 0);
        String sql = md.getSqlOfSystem(name, isRecycle, action, what, kind, orderBy, sort, actionType);
        int total = md.getObjectCount(sql);

        Vector v = md.list(sql, (curpage - 1) * pagesize, curpage * pagesize - 1);
        for (Object o : v) {
            md = (MessageDb) o;
            int id = md.getId();
            String title = md.getTitle();
            String sender = md.getSender();
            String sendTime = md.getSendTime();
            boolean isReaded = md.isReaded();
            JSONObject json = new JSONObject();
            json.put("id", id);
            json.put("isReaded", isReaded);
            if (!sender.equals(MessageDb.SENDER_SYSTEM)) {
                sender = userCache.getUser(sender).getRealName();
            }
            json.put("sender", sender);
            json.put("sendTime", sendTime);
            json.put("kind", MessageMgr.getActionName(md.getActionType()));
            json.put("isReaded", isReaded);
            json.put("title", title);
            ary.add(json);
        }

        JSONObject json = new JSONObject();
        json.put("list", ary);
        json.put("total", total);
        json.put("page", curpage);

        return new Result<>(json);
    }

    @ApiOperation(value = "系统信息展示页面", notes = "系统信息展示页面", httpMethod = "GET")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @RequestMapping(value = "/sysMessageShowPage")
    @ResponseBody
    public Result<Object> sysMessageShowPage() {
        MessageMgr messageMgr = new MessageMgr();
        int id = ParamUtil.getInt(request, "id", -1);
        MessageDb md = null;
        try {
            md = messageMgr.getMessageDb(id);
        } catch (ErrMsgException e) {
            LogUtil.getLog(getClass()).error(e);
        }
        if (md == null || !md.isLoaded()) {
            return new Result<>(false);
        }

        // 防止水平越权访问
        Privilege privilege = new Privilege();
        if (!md.getReceiver().equals(privilege.getUser(request)) && !privilege.isUserPrivValid(request, ConstUtil.PRIV_ADMIN)) {
            return new Result<>(false, "权限非法");
        }

        String title, content, rq, receiver, sender;
        int type;
        id = md.getId();
        title = md.getTitle();
        content = md.getContent();
        type = md.getType();
        rq = md.getRq();
        receiver = md.getReceiver();
        sender = md.getSender();

        UserMgr um = new UserMgr();
        String senderName = sender;
        if (!sender.equals(MessageDb.SENDER_SYSTEM)) {
            senderName = um.getUserDb(sender).getRealName();
        }

        if (md.getBox() == MessageDb.INBOX && receiver.equals(privilege.getUser(request))) {
            md.setReaded(true);
            md.save();
        }

        JSONObject object = new JSONObject();

        object.put("title", title);
        object.put("content", cn.js.fan.util.StrUtil.ubb(request, MessageDb.toHtml(content), true));
        object.put("receiver", receiver);
        object.put("senderName", senderName);

        object.put("actionType", md.getActionType());
        object.put("action", md.getAction());
        object.put("actionSubType", md.getActionSubType());
        // 兼容6.0前旧版本
        String[] ary = StrUtil.split(md.getAction(), "\\|");
        Map<String, String> map = null;
        if (ary != null) {
            int len = ary.length;
            if (len >= 1) {
                map = new HashMap<>();
                for (String s : ary) {
                    String[] pair = s.split("=");
                    if (pair.length == 2) {
                        map.put(pair[0], pair[1]);
                    }
                }
            }
        }

        if (MessageDb.ACTION_FLOW_DISPOSE.equals(md.getActionType())) {
            String strMyActionId;
            if (map != null && map.size() > 0) {
                strMyActionId = map.get("myActionId");
            } else {
                strMyActionId = md.getAction();
            }
            object.put("visitKey", SecurityUtil.makeVisitKey(md.getAction()));
            // 判断待办流程是否已被处理
            long myActionId = StrUtil.toLong(strMyActionId, -1);
            if (myActionId != -1) {
                MyActionDb mad = new MyActionDb();
                mad = mad.getMyActionDb(myActionId);
                WorkflowDb wf = new WorkflowDb();
                wf = wf.getWorkflowDb((int) mad.getFlowId());
                if (wf != null) {
                    Leaf lf = new Leaf();
                    lf = lf.getLeaf(wf.getTypeCode());
                    if (lf != null) {
                        object.put("flowType", lf.getType());
                        if (mad.isChecked()) {
                            if (mad.getCheckStatus() != MyActionDb.CHECK_STATUS_NOT) {
                                object.put("actionType", MessageDb.ACTION_FLOW_SHOW);
                                object.put("action", mad.getFlowId());
                                object.put("actionName", "点击查看流程处理过程");
                            }
                        } else {
                            object.put("actionType", MessageDb.ACTION_FLOW_DISPOSE);
                            object.put("action", mad.getId());
                            object.put("actionName", "点击处理流程");
                        }
                    } else {
                        LogUtil.getLog(getClass()).error("流程: " + mad.getFlowId() + " 的类型: " + wf.getTypeCode() + " 不存在");
                    }
                } else {
                    LogUtil.getLog(getClass()).error("流程: " + mad.getFlowId() + " 不存在");
                }
            } else {
                object.put("actionType", "");
                object.put("action", -1);
                object.put("actionName", "待办记录已不存在");
            }
        } else if (MessageDb.ACTION_FLOW_SHOW.equals(md.getActionType())) {
            String strFlowId;
            if (map != null && map.size() > 0) {
                strFlowId = map.get("flowId");
            } else {
                strFlowId = md.getAction();
            }
            int flowId = StrUtil.toInt(strFlowId, -1);
            object.put("action", flowId);
            if (flowId == -1) {
                object.put("actionName", "流程已被删除");
            } else {
                com.redmoon.oa.sso.Config config = new com.redmoon.oa.sso.Config();
                String desKey = config.get("key");
                // 以flowId作为值加密
                String visitKey = ThreeDesUtil.encrypt2hex(desKey, String.valueOf(flowId));
                object.put("visitKey", visitKey);
                object.put("actionName", "点击查看流程处理过程");
            }
        } else if (MessageDb.ACTION_MODULE_EDIT.equals(md.getActionType())) {
            String visitKey = SecurityUtil.makeVisitKey(md.getAction());
            String moduleCode = md.getActionSubType();
            ModuleSetupDb msd = new ModuleSetupDb();
            msd = msd.getModuleSetupDb(moduleCode);
            object.put("visitKey", visitKey);
            object.put("actionName", "点击查看" + msd.getName());
        } else if (MessageDb.ACTION_MODULE_SHOW.equals(md.getActionType())) {
            String visitKey = SecurityUtil.makeVisitKey(md.getAction());
            String moduleCode = md.getActionSubType();
            ModuleSetupDb msd = new ModuleSetupDb();
            msd = msd.getModuleSetupDb(moduleCode);
            object.put("visitKey", visitKey);
            object.put("actionName", "点击查看" + msd.getName());
        }

        /*String actionLink = md.renderAction(request);
        object.put("hasLink", !StrUtil.isEmpty(actionLink));
        object.put("actionLink", actionLink);*/

        object.put("attachments", md.getAttachments());
        object.put("id", id);
        object.put("rq", rq);

        return new Result<>(object);
    }

    @ApiOperation(value = "获取信息类型", notes = "获取信息类型", httpMethod = "GET")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @RequestMapping(value = "/getMessageType")
    @ResponseBody
    public Result<Object> getMessageType() {
        JSONArray arr = MessageMgr.getActionTypes();
        return new Result<>(arr);
    }

    @ApiOperation(value = "获取新信息", notes = "获取新信息", httpMethod = "POST")
    @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
    @ResponseBody
    @RequestMapping(value = "/getNewMsgsOfUser", method = {RequestMethod.POST, RequestMethod.GET}, produces = {"text/html;charset=UTF-8;", "application/json;charset=UTF-8;"})
    public Result<Object> getNewMsgsOfUser() {
        MessageDb md = new MessageDb();
        return new Result<>(md.getNewMsgsOfUser(new Privilege().getUser(request)));
    }

    @ApiOperation(value = "内部邮件收件箱列表", notes = "内部邮件收件箱列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/listInbox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listInbox(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer pageSize) {
        String name = authUtil.getUserName();
        MessageDb md = new MessageDb();
        String sql = md.getListSql(request, name);

        int total = md.getObjectCount(sql);
        Vector v = md.list(sql, (page - 1) * pageSize, page * pageSize - 1);
        JSONArray ary = (JSONArray)JSONArray.toJSON(v);
        for (Object o : ary) {
            JSONObject json = (JSONObject) o;

            String senderRealName = "";
            String sender = json.getString("sender");
            if (sender.startsWith("dept@")) {
                String deptCode = sender.substring(5);
                Department department = departmentCache.getDepartment(deptCode);
                if (department == null) {
                    senderRealName = "部门不存在";
                } else {
                    senderRealName = department.getName();
                }
            } else {
                User user = userCache.getUser(sender);
                senderRealName = user != null ? user.getRealName() : "不存在";
            }
            json.put("senderRealName", senderRealName);

            if (!StrUtil.isEmpty(json.getString("receiver"))) {
                String receiverRealName = "";
                String receiver = json.getString("receiver");
                if (receiver.startsWith("dept@")) {
                    String deptCode = receiver.substring(5);
                    Department department = departmentCache.getDepartment(deptCode);
                    if (department == null) {
                        receiverRealName = "部门不存在";
                    } else {
                        receiverRealName = department.getName();
                    }
                } else {
                    User user = userCache.getUser(receiver);
                    receiverRealName = user != null ? user.getRealName() : "不存在";
                }
                json.put("receiverRealName", receiverRealName);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", ary);
        jsonObject.put("total", total);
        return new Result<>(jsonObject);
    }

    @ApiOperation(value = "内部邮件草稿箱列表", notes = "内部邮件草稿箱列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/listDraft", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listDraft(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer pageSize) {
        String name = authUtil.getUserName();
        MessageDb md = new MessageDb();
        String sql = md.getListDraftSql(name);

        int total = md.getObjectCount(sql);
        Vector v = md.list(sql, (page - 1) * pageSize, page * pageSize - 1);
        JSONArray ary = (JSONArray)JSONArray.toJSON(v);
        for (Object o : ary) {
            JSONObject json = (JSONObject) o;
            String senderRealName = "";
            String sender = json.getString("sender");
            if (sender.startsWith("dept@")) {
                String deptCode = sender.substring(5);
                Department department = departmentCache.getDepartment(deptCode);
                if (department == null) {
                    senderRealName = "部门不存在";
                } else {
                    senderRealName = department.getName();
                }
            } else {
                User user = userCache.getUser(sender);
                senderRealName = user != null ? user.getRealName() : "不存在";
            }
            json.put("senderRealName", senderRealName);

            if (!StrUtil.isEmpty(json.getString("receiversjs"))) {
                StringBuilder sb = new StringBuilder(5);
                String[] aryReceiver = json.getString("receiversjs").split(",");
                for (String receiver : aryReceiver) {
                    String receiverRealName = "";
                    if (receiver.startsWith("dept@")) {
                        String deptCode = receiver.substring(5);
                        Department department = departmentCache.getDepartment(deptCode);
                        if (department == null) {
                            receiverRealName = "部门不存在";
                        } else {
                            receiverRealName = department.getName();
                        }
                    } else {
                        User user = userCache.getUser(receiver);
                        receiverRealName = user != null ? user.getRealName() : "不存在";
                    }
                    StrUtil.concat(sb, ",", receiverRealName);
                }
                json.put("receiversjsRealName", sb.toString());
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", ary);
        jsonObject.put("total", total);
        return new Result<>(jsonObject);
    }

    @ApiOperation(value = "内部邮件发件箱列表", notes = "内部邮件发件箱列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/listOutbox", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listOutbox(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer pageSize) {
        String name = authUtil.getUserName();
        MessageDb md = new MessageDb();
        String sql = md.getListOutBoxSql(request, name);

        int total = md.getObjectCount(sql);
        Vector v = md.list(sql, (page - 1) * pageSize, page * pageSize - 1);

        JSONArray ary = (JSONArray)JSONArray.toJSON(v);
        for (Object o : ary) {
            JSONObject json = (JSONObject) o;

            String senderRealName = "";
            String sender = json.getString("sender");
            if (sender.startsWith("dept@")) {
                String deptCode = sender.substring(5);
                Department department = departmentCache.getDepartment(deptCode);
                if (department == null) {
                    senderRealName = "部门不存在";
                } else {
                    senderRealName = department.getName();
                }
            } else {
                User user = userCache.getUser(sender);
                senderRealName = user != null ? user.getRealName() : "不存在";
            }
            json.put("senderRealName", senderRealName);

            if (!StrUtil.isEmpty(json.getString("receiversjs"))) {
                StringBuilder sb = new StringBuilder(5);
                String[] aryReceiver = json.getString("receiversjs").split(",");
                for (String receiver : aryReceiver) {
                    String receiverRealName = "";
                    if (receiver.startsWith("dept@")) {
                        String deptCode = receiver.substring(5);
                        Department department = departmentCache.getDepartment(deptCode);
                        if (department == null) {
                            receiverRealName = "部门不存在";
                        } else {
                            receiverRealName = department.getName();
                        }
                    } else {
                        User user = userCache.getUser(receiver);
                        receiverRealName = user != null ? user.getRealName() : "不存在";
                    }
                    StrUtil.concat(sb, ",", receiverRealName);
                }
                json.put("receiversjsRealName", sb.toString());
            }

            json.put("isSent",json.getIntValue("isSent") == 1 ? "是" : "否");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", ary);
        jsonObject.put("total", total);
        return new Result<>(jsonObject);
    }

    @ApiOperation(value = "内部邮件垃圾箱列表", notes = "内部邮件垃圾箱列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/listCycle", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listCycle(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer pageSize) {
        String name = authUtil.getUserName();
        MessageDb md = new MessageDb();
        String sql = md.getListRecycleSql(request, name);

        int total = md.getObjectCount(sql);
        Vector v = md.list(sql, (page - 1) * pageSize, page * pageSize - 1);
        JSONArray ary = (JSONArray)JSONArray.toJSON(v);
        for (Object o : ary) {
            JSONObject json = (JSONObject) o;
            String senderRealName = "";
            String sender = json.getString("sender");
            if (sender.startsWith("dept@")) {
                String deptCode = sender.substring(5);
                Department department = departmentCache.getDepartment(deptCode);
                if (department == null) {
                    senderRealName = "部门不存在";
                } else {
                    senderRealName = department.getName();
                }
            } else {
                User user = userCache.getUser(sender);
                senderRealName = user != null ? user.getRealName() : "不存在";
            }
            json.put("senderRealName", senderRealName);

            if (!StrUtil.isEmpty(json.getString("receiversjs"))) {
                StringBuilder sb = new StringBuilder(5);
                String[] aryReceiver = json.getString("receiversjs").split(",");
                for (String receiver : aryReceiver) {
                    String receiverRealName = "";
                    if (receiver.startsWith("dept@")) {
                        String deptCode = receiver.substring(5);
                        Department department = departmentCache.getDepartment(deptCode);
                        if (department == null) {
                            receiverRealName = "部门不存在";
                        } else {
                            receiverRealName = department.getName();
                        }
                    } else {
                        User user = userCache.getUser(receiver);
                        receiverRealName = user != null ? user.getRealName() : "不存在";
                    }
                    StrUtil.concat(sb, ",", receiverRealName);
                }
                json.put("receiversjsRealName", sb.toString());
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", ary);
        jsonObject.put("total", total);
        return new Result<>(jsonObject);
    }

    @ApiOperation(value = "发送内部邮件", notes = "发送内部邮件", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/sendMsg", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> sendMsg() {
        MessageMgr messageMgr = new MessageMgr();
        return new Result<>(messageMgr.addMsg(request.getSession().getServletContext(), request));
    }

    @ApiOperation(value = "保存内部邮件草稿", notes = "保存内部邮件草稿", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/saveDraft", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> saveDraft() {
        MessageMgr messageMgr = new MessageMgr();
        return new Result<>(messageMgr.AddDraftMsg(request.getSession().getServletContext(), request));
    }

    @ApiOperation(value = "查看内部邮件", notes = "查看内部邮件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/show", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> show(@RequestParam Integer id) {
        MessageMgr messageMgr = new MessageMgr();
        MessageDb md = messageMgr.getMessageDb(id);
        if (!md.isLoaded()) {
            return new Result<>(false, "邮件不存在");
        }
        JSONObject json = (JSONObject) JSONObject.toJSON(md);

        String receiversjs = md.getReceiversjs();
        String receiverscs = md.getReceiverscs();
        String receiversms = md.getReceiversms();

        String realNamejs = "";
        if (receiversjs != null && !"".equals(receiversjs)) {
            String[] recjsArr = receiversjs.split(",");
            for (String receiver : recjsArr) {
                String receiverRealName = "";
                if (receiver.startsWith("dept@")) {
                    String deptCode = receiver.substring(5);
                    Department department = departmentCache.getDepartment(deptCode);
                    if (department == null) {
                        receiverRealName = "部门不存在";
                    } else {
                        receiverRealName = department.getName();
                    }
                } else {
                    User user = userCache.getUser(receiver);
                    receiverRealName = user != null ? user.getRealName() : "不存在";
                }
                if ("".equals(realNamejs)) {
                    realNamejs = receiverRealName;
                } else {
                    realNamejs += "," + receiverRealName;
                }
            }
        }
        // 收件人
        json.put("realNameJs", realNamejs);

        String realNameAll = "";
        if (receiverscs != null && !"".equals(receiverscs)) {
            String[] recArry = receiverscs.split(",");
            for (String s : recArry) {
                UserDb udb1 = new UserDb();
                udb1 = udb1.getUserDb(s);
                if ("".equals(realNameAll)) {
                    realNameAll = udb1.getRealName();
                } else {
                    realNameAll += "," + udb1.getRealName();
                }
            }
        }
        json.put("realNameCs", realNameAll);

        String uName = authUtil.getUserName();
        String sender = md.getSender();

        String realNameAll2 = "";
        if (sender.equals(uName) && receiversms != null && !"".equals(receiversms)) {
            String[] recArry = receiversms.split(",");
            for (String s : recArry) {
                UserDb udb1 = new UserDb();
                udb1 = udb1.getUserDb(s);
                if ("".equals(realNameAll2)) {
                    realNameAll2 = udb1.getRealName();
                } else {
                    realNameAll2 += "," + udb1.getRealName();
                }
            }
        }
        json.put("realNameMs", realNameAll2);

        Config cfg = Config.getInstance();
        json.put("isMobileForbidDownload", cfg.getBoolean("isMobileForbidDownload"));

        if (md.getBox()==MessageDb.INBOX && md.getReceiver().equals(authUtil.getUserName())) {
            md.setReaded(true);
            md.save();
        }
        return new Result<>(json);
    }

    @ApiOperation(value = "编辑内部邮件草稿页面", notes = "编辑内部邮件草稿页面", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/editDraftPage", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> editDraftPage(Integer id) {
        MessageMgr messageMgr = new MessageMgr();
        MessageDb md = messageMgr.getMessageDb(id);
        if (!md.isLoaded()) {
            return new Result<>(false, "邮件不存在");
        }
        JSONObject json = (JSONObject) JSONObject.toJSON(md);

        String receiversjs = md.getReceiversjs();
        String receiverscs = md.getReceiverscs();
        String receiversms = md.getReceiversms();

        String realNamejs = "";
        if (receiversjs != null && !"".equals(receiversjs)) {
            String[] recjsArr = receiversjs.split(",");
            for (String receiver : recjsArr) {
                String receiverRealName = "";
                if (receiver.startsWith("dept@")) {
                    String deptCode = receiver.substring(5);
                    Department department = departmentCache.getDepartment(deptCode);
                    if (department == null) {
                        receiverRealName = "部门不存在";
                    } else {
                        receiverRealName = department.getName();
                    }
                } else {
                    User user = userCache.getUser(receiver);
                    receiverRealName = user != null ? user.getRealName() : "不存在";
                }
                if ("".equals(realNamejs)) {
                    realNamejs = receiverRealName;
                } else {
                    realNamejs += "," + receiverRealName;
                }
            }
        }
        // 收件人
        json.put("realNameJs", realNamejs);

        String realNameAll = "";
        if (receiverscs != null && !"".equals(receiverscs)) {
            String[] recArry = receiverscs.split(",");
            for (String s : recArry) {
                UserDb udb1 = new UserDb();
                udb1 = udb1.getUserDb(s);
                if ("".equals(realNameAll)) {
                    realNameAll = udb1.getRealName();
                } else {
                    realNameAll += "," + udb1.getRealName();
                }
            }
        }
        json.put("realNameCs", realNameAll);

        String uName = authUtil.getUserName();
        String sender = md.getSender();

        String realNameAll2 = "";
        if (sender.equals(uName) && receiversms != null && !"".equals(receiversms)) {
            String[] recArry = receiversms.split(",");
            for (String s : recArry) {
                UserDb udb1 = new UserDb();
                udb1 = udb1.getUserDb(s);
                if ("".equals(realNameAll2)) {
                    realNameAll2 = udb1.getRealName();
                } else {
                    realNameAll2 += "," + udb1.getRealName();
                }
            }
        }
        json.put("realNameMs", realNameAll2);

        Config cfg = Config.getInstance();
        json.put("isMobileForbidDownload", cfg.getBoolean("isMobileForbidDownload"));
        return new Result<>(json);
    }

    @ApiOperation(value = "保存内部邮件草稿", notes = "保存内部邮件草稿", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/updateDraft", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> updateDraft() {
        FileUpload fileUpload = new FileUpload();
        if (ParamUtil.isMobile(request)) {
            fileUpload.fillParams(request);
        } else {
            Config cfg = Config.getInstance();
            fileUpload.setMaxAllFileSize(cfg.getInt("shortMsgFileSize"));
            String exts = cfg.get("shortMsgFileExt");
            String[] extAry = StrUtil.split(exts, ",");
            if (extAry != null) {
                fileUpload.setValidExtname(extAry);
            }
            try {
                int ret = fileUpload.doUpload(request.getSession().getServletContext(), request);
                if (ret != FileUpload.RET_SUCCESS) {
                    if (ret == FileUpload.RET_INVALIDEXT) {
                        // 手机端可能上传有空文件
                        if (!ParamUtil.isMobile(request)) {
                            throw new ErrMsgException("ret=" + ret + " " + fileUpload.getErrMessage());
                        }
                    }
                }
            } catch (IOException e) {
                LogUtil.getLog(getClass()).error("doUpload:" + e.getMessage());
            }
        }

        int id = StrUtil.toInt(fileUpload.getFieldValue( "id"), 0);
        String receiversAll = fileUpload.getFieldValue( "receiver");
        String title = fileUpload.getFieldValue( "title");
        String content = fileUpload.getFieldValue( "content");
        int isSent = "yes".equals(fileUpload.getFieldValue( "send_now")) ? 1 : 0;
        String sendTime = fileUpload.getFieldValue( "send_time");
        int receiptState = StrUtil.toInt(fileUpload.getFieldValue( "receipt_state"), 0);
        int msgLevel = StrUtil.toInt(fileUpload.getFieldValue( "msg_level"), 0);
        String receiverscs1 = fileUpload.getFieldValue( "receiver1");
        String receiversms1 = fileUpload.getFieldValue( "receiver2");
        String receiversjs1 = fileUpload.getFieldValue( "receiver");

        MessageDb msg = new MessageDb();
        msg = (MessageDb)msg.getMessageDb(id);
        if (!"".equals(receiverscs1)) {
            receiversAll += "," + receiverscs1;
        }
        if (!"".equals(receiversms1)) {
            receiversAll += "," + receiversms1;
        }
        msg.setReceiversAll(receiversAll);
        msg.setTitle(title);
        msg.setContent(content);
        msg.setIsSent(isSent);
        msg.setSendTime(sendTime);
        msg.setReceiptState(receiptState);
        msg.setMsgLevel(msgLevel);
        msg.setReceiverscs(receiverscs1);
        msg.setReceiversms(receiversms1);
        msg.setReceiversjs(receiversjs1);

        boolean re = msg.save();
        if (re) {
            if (ParamUtil.isMobile(request)) {
                String attachments = fileUpload.getFieldValue("attachments");
                if (!StrUtil.isEmpty(attachments)) {
                    Attachment att = new Attachment();
                    att.updateMsgId(attachments, id);
                }
            } else {
                Calendar cal = Calendar.getInstance();
                String year = "" + (cal.get(Calendar.YEAR));
                String month = "" + (cal.get(Calendar.MONTH) + 1);

                com.redmoon.oa.Config cfg = new com.redmoon.oa.Config();
                String vpath = cfg.get("file_message") + "/" + year + "/" + month + "/";
                Vector<FileInfo> v = fileUpload.getFiles();
                IFileService fileService = SpringUtil.getBean(IFileService.class);
                for (FileInfo fi : v) {
                    fileService.write(fi, vpath);
                    Attachment att = new Attachment();
                    att.setMsgId(id);
                    att.setName(fi.getName());
                    att.setDiskName(fi.getDiskName());
                    att.setVisualPath(vpath);
                    att.setSize(fi.getSize());
                    att.create();
                }
            }
        }
        return new Result<>(re);
    }

    @ApiOperation(value = "发送内部邮件草稿或转发内部邮件", notes = "发送内部邮件草稿或转发内部邮件", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/transmit", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> transmit() {
        MessageMgr messageMgr = new MessageMgr();
        ServletContext application = request.getSession().getServletContext();
        return new Result<>(messageMgr.TransmitMsg(application, request));
    }

    @ApiOperation(value = "回复", notes = "回复", httpMethod = "POST")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/reply", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> reply() {
        MessageMgr messageMgr = new MessageMgr();
        ServletContext application = request.getSession().getServletContext();
        return new Result<>(messageMgr.addMsg(application, request));
    }

    @ApiOperation(value = "会话列表", notes = "会话列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sender", value = "发送者", required = true, dataType = "String"),
            @ApiImplicitParam(name = "receiver", value = "接收者", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isRecycle", value = "是否回收站", required = true, dataType = "Boolean"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/listChat", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listChat(@RequestParam String sender, @RequestParam String receiver, @RequestParam(defaultValue = "false") Boolean isRecycle) {
        String sql = "select id from oa_message where ((sender = "+StrUtil.sqlstr(sender)+" and receiver = "+StrUtil.sqlstr(receiver)+") or (sender = "+StrUtil.sqlstr(receiver)+" and receiver = "+StrUtil.sqlstr(sender)+")) ";
        if(isRecycle){
            sql += " and is_dustbin = 1 and is_sender_dustbin = 1 ";
        }else{
            sql += " and is_dustbin = 0 and is_sender_dustbin = 0 ";
        }
        sql += " order by send_time desc";
        MessageDb messageDb = new MessageDb();
        Vector v = messageDb.list(sql);
        /*for (Object o : v) {
            MessageDb md = (MessageDb)o;
            md.loadAttachment();
        }*/
        return new Result<>(JSONArray.toJSON(v));
    }

    @ApiOperation(value = "撤回", notes = "撤回", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/recall", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> recall(@RequestParam Integer id) {
        MessageDb msg = new MessageDb();
        boolean re = msg.doReturn(authUtil.getUserName(), id);
        return new Result<>(re);
    }

    @ApiOperation(value = "取部门邮箱被代理的信息", notes = "取部门邮箱被代理的信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptCode", value = "部门编码", required = true, dataType = "String"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/getAgentInfo", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> getAgentInfo(@RequestParam String deptCode) {
        OaMessageDept oaMessageDept = oaMessageDeptService.getByDeptCode(deptCode);
        if (oaMessageDept == null) {
            JSONObject json = new JSONObject();
            json.put("isDeptMgr", new Privilege().isUserPrivValid(request, "deptEmail"));
            return new Result<>(json);
        }
        else {
            JSONObject json = (JSONObject)JSONObject.toJSON(oaMessageDept);
            if (oaMessageDept.getAgented()) {
                Department department = departmentCache.getDepartment(oaMessageDept.getAgentDeptCode());
                if (department != null) {
                    json.put("agentDeptName", department.getName());
                }
            }
            json.put("isDeptMgr", new Privilege().isUserPrivValid(request, "dept.email.manager"));
            return new Result<>(json);
        }
    }

    @ApiOperation(value = "置部门邮箱代理", notes = "置部门邮箱代理", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptCode", value = "部门编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "agentDeptCode", value = "代理部门编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "agentDate", value = "代理期限", required = true, dataType = "Date"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/setAgent", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> setAgent(@RequestParam String deptCode, @RequestParam String agentDeptCode, @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date agentDate) {
        return new Result<>(oaMessageDeptService.setAgent(deptCode, agentDeptCode, agentDate));
    }

    @ApiOperation(value = "取消部门邮箱代理", notes = "取消部门邮箱代理", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptCode", value = "部门编码", required = true, dataType = "String"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/cancelAgent", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> cancelAgent(@RequestParam String deptCode) {
        boolean re = oaMessageDeptService.cancelAgent(deptCode);
        if (re) {
            return new Result<>();
        } else {
            return new Result<>(false, "代理未设置");
        }
    }

    @ApiOperation(value = "上传文件", notes = "上传文件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "MultipartFile"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> upload(@RequestParam(value = "file") MultipartFile file) {
        // 置保存路径
        Calendar cal = Calendar.getInstance();
        String year = "" + (cal.get(Calendar.YEAR));
        String month = "" + (cal.get(Calendar.MONTH) + 1);

        com.redmoon.oa.Config cfg = Config.getInstance();
        String vpath = cfg.get("file_message") + "/" + year + "/" + month + "/";

        String name = file.getOriginalFilename();
        String ext = StrUtil.getFileExt(name);
        String diskName = FileUpload.getRandName() + "." + ext;
        String previewUrl = "";

        Attachment att = new Attachment();
        att.setMsgId(0);
        att.setName(name);
        att.setDiskName(diskName);
        att.setVisualPath(vpath);
        att.setSize(file.getSize());
        att.setCreateTime(new Date());
        boolean re = att.create();
        if (re) {
            try {
                fileService.write(file, vpath, diskName);

                boolean canOfficeFilePreview = cfg.getBooleanProperty("canOfficeFilePreview");
                boolean canPdfFilePreview = cfg.getBooleanProperty("canPdfFilePreview");
                boolean isGenPreview = false;
                if (canOfficeFilePreview) {
                    if (FileUtil.isOfficeFile(diskName)) {
                        isGenPreview = true;
                    }
                }
                if (canPdfFilePreview) {
                    if ("pdf".equals(ext)) {
                        isGenPreview = true;
                    }
                }

                if (isGenPreview) {
                    //设置子线程共享，否则会报：No thread-bound request found，注意parallelStream数据量少的时候，反而运行效率不高
                    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                    RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);

                    PreviewGenerateThread previewGenerateThread = new PreviewGenerateThread(vpath, diskName);
                    previewGenerateThread.start();
                    previewUrl = sysUtil.getRootPath() + "/" + vpath + "/" + diskName.substring(0, diskName.lastIndexOf(".")) + ".html";
                }
            } catch (IOException e) {
                LogUtil.getLog(getClass()).error(e);
            }
        }
        JSONObject json = new JSONObject();
        json.put("id", att.getId());
        json.put("name", att.getName());
        json.put("visualPath", vpath);
        json.put("diskName", diskName);
        json.put("size", att.getSize());
        json.put("previewUrl", previewUrl);
        return new Result<>(json);
    }

    @ApiOperation(value = "删除邮件附件", notes = "删除邮件附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "attId", value = "附件ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/delAttachment", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> delAttachment(@RequestParam Integer attId) {
        MessageDb md = new MessageDb();
        Attachment attachment = new Attachment(attId);
        md = (MessageDb)md.getMessageDb(attachment.getMsgId());
        Privilege privilege = new Privilege();
        if (privilege.isUserPrivValid(request, "admin") || md.getSender().equals(authUtil.getUserName())) {
            return new Result<>(md.delAttachment(attachment));
        } else {
            return new Result<>(false, "权限非法");
        }
    }
}
